<template>
    <div class="tab-content">
        <!-- 标点列表 -->
        <div class="map-points-header">
            <h3>地图标点列表</h3>
            <div class="header-buttons">
                <el-button type="primary" @click="openAddPointDialog">添加标点</el-button>
                <el-button type="success" @click="openPointTypeConfigDialog">配置标点类型</el-button>
            </div>
        </div>

        <el-table :data="securityForm.mapPoints" border style="width: 100%; margin-bottom: 20px;">
            <el-table-column prop="name" label="点位名称" align="center"/>
            <el-table-column prop="type" label="点位类型" align="center">
                <template #default="{ row }">
                    <el-tag
                        :type="getPointTypeTag(row.type)">{{
                        getPointTypeName(row.type) }}</el-tag>
                </template>
            </el-table-column>
            <!-- 图标 -->
            <el-table-column label="图标" align="center">
                <template #default="{ row }">
                    <div style="width: 100%;display: flex;justify-content: center;">
                        <img v-if="row.icon" :src="row.icon" alt="图标" style="width: 30px; height: 30px; object-fit: cover; border-radius: 4px;" />
                        <span v-else style="color: #999;">无图标</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="longitude" label="经度" align="center"/>
            <el-table-column prop="latitude" label="纬度" align="center"/>
            <el-table-column label="操作">
                <template #default="{ row, $index }">
                    <el-button size="small" type="primary" @click="editPoint(row, $index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deletePoint($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 标点类型配置弹窗 -->
        <el-dialog v-model="pointTypeConfigVisible" title="标点类型配置" width="800px">
            <div class="point-type-config">
                <div class="config-header">
                    <el-button type="primary" @click="addPointType">添加标点类型</el-button>
                </div>
                
                <el-table :data="pointTypes" border style="width: 100%; margin-top: 20px;">
                    <el-table-column prop="key" label="类型标识" width="120" />
                    <el-table-column prop="name" label="类型名称" width="150" />
                    <el-table-column label="图标" width="100">
                        <template #default="{ row }">
                            <img v-if="row.icon" :src="row.icon" alt="图标" style="width: 30px; height: 30px; object-fit: cover; border-radius: 4px;" />
                            <span v-else style="color: #999;">无图标</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="{ row, $index }">
                            <el-button size="small" type="primary" @click="editPointType(row, $index)">编辑</el-button>
                            <el-button size="small" type="danger" @click="deletePointType($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="pointTypeConfigVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 标点类型编辑弹窗 -->
        <el-dialog v-model="pointTypeEditVisible" title="编辑标点类型" width="600px">
            <el-form ref="pointTypeFormRef" :model="pointTypeForm" :rules="pointTypeRules" label-width="100px">
                <el-form-item label="类型标识" prop="key">
                    <el-input v-model="pointTypeForm.key" placeholder="请输入类型标识（如：solar）" />
                    <!-- :disabled="currentPointTypeIndex >= 0"  -->
                </el-form-item>
                
                <el-form-item label="类型名称" prop="name">
                    <el-input v-model="pointTypeForm.name" placeholder="请输入类型名称（如：绿电供应）" />
                </el-form-item>
                <el-form-item label="图标" prop="icon">
                    <div class="icon-upload-section">
                        <div v-if="pointTypeForm.icon" class="current-icon">
                            <img :src="pointTypeForm.icon" style="width: 50px; height: 50px; object-fit: cover; border: 1px solid #ddd; border-radius: 4px;" />
                            <!-- <el-button size="small" type="danger" @click="removeIcon" style="margin-left: 10px;">删除图标</el-button> -->
                        </div>
                        <UploadComponent 
                            :type="'image'" 
                            :multiple="false" 
                            :limit="1"
                            @success="handleIconUploadType">

                            <el-button type="primary">{{ pointTypeForm.icon ? '更换图标' : '上传图标' }}</el-button>
                        </UploadComponent>
                    </div>
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="pointTypeEditVisible = false">取消</el-button>
                    <el-button type="primary" @click="savePointType">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 标点配置弹窗 -->
        <el-dialog v-model="pointDialogVisible" title="标点配置" width="1200px" class="point-dialog" style="height: 80vh;">
            <div class="dialog-content">
                <div class="form-section">
                    <h4>标点信息</h4>
                    <el-form ref="pointFormRef" :model="pointForm" :rules="pointRules" label-width="100px">
                        <el-form-item label="点位名称" prop="name">
                            <el-input v-model="pointForm.name" placeholder="请输入点位名称" />
                        </el-form-item>
                        <el-form-item label="点位类型" prop="type">
                            <el-select v-model="pointForm.type" placeholder="请选择点位类型" @change="handleTypeChange">

                                <el-option 
                                    v-for="pointType in pointTypes" 
                                    :key="pointType.key" 
                                    :label="pointType.name" 
                                    :value="pointType.key" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="经度" prop="longitude">
                            <el-input-number v-model="pointForm.longitude" :precision="6" :controls="false"
                                placeholder="请输入经度" style="width: 100%" />
                        </el-form-item>
                        <el-form-item label="纬度" prop="latitude">
                            <el-input-number v-model="pointForm.latitude" :precision="6" :controls="false" placeholder="请输入纬度"
                                style="width: 100%" />
                        </el-form-item>
                        <el-form-item label="图标" prop="icon">
                            <div class="icon-upload-section">
                                <div  class="current-icon" style="width: 50px; height: 50px;border: 1px solid #ddd; border-radius: 4px;">
                                    <img v-if="pointForm.icon" :src="pointForm.icon" style="width: 100%; height: 100%; object-fit: cover;" />
                                    <!-- <el-button size="small" type="danger" @click="removeIcon" style="margin-left: 10px;">删除图标</el-button> -->
                                </div>
                                <!-- <UploadComponent 
                                    :type="'image'" 
                                    :multiple="false" 
                                    :limit="1"
                                    @success="handleIconUpload">
                                    <el-button type="primary">{{ pointForm.icon ? '更换图标' : '上传图标' }}</el-button>
                                </UploadComponent> -->
                            </div>
                        </el-form-item>
                    </el-form>
                </div>

                <div class="map-section">
                    <h4>地图选点</h4>
                    <div id="amap-container" class="amap-container"></div>
                    <div class="map-actions">
                        <el-button type="primary" @click="getLocationFromMap">初始化地图/重新获取</el-button>
                        <!-- <el-button @click="destroyMap">清除地图</el-button> -->
                    </div>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelPoint">取消</el-button>
                    <el-button type="primary" @click="savePoint">确定</el-button>
                </span>
            </template>
        </el-dialog>



        <div class="save-button-container">
            <el-button type="primary" @click="saveSecurityData">保存地图标点配置</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { ref, reactive } from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { Plus } from '@element-plus/icons-vue'
    import { updateDataClassify } from '@/api/port'
    import AMapLoader from '@amap/amap-jsapi-loader'
    import UploadComponent from '@/components/upload/index.vue'

    // 定义
    // 模块8: 地图标点配置表单（高德地图版本）
    const securityForm = reactive({
        mapPoints: [] as Array<{
            name: string
            type: string
            longitude: number
            latitude: number
            icon: string
        }>
    })
    
    // 标点类型配置 
    const pointTypes = ref<any[]>([
        // { key: 'solar', name: '绿电供应', icon: '' },
        // { key: 'battery', name: '共享换电', icon: '' },
        // { key: 'travel', name: '共享出行', icon: '' },
        // { key: 'transport', name: '共享运力', icon: '' }
    ])
    
    // 标点类型配置弹窗相关
    const pointTypeConfigVisible = ref(false)
    const pointTypeEditVisible = ref(false)
    const currentPointTypeIndex = ref(-1)
    const pointTypeForm = reactive({
        key: '',
        name: '',
        icon: ''
    })
    
    // 标点类型表单验证规则
    const pointTypeRules = {
        key: [{ required: true, message: '类型标识不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }]
    }
    // 数字范围验证函数
    const validateNumberLog = (rule: any, value: any, callback: (error?: Error) => void) => {
        if (value !== undefined && value !== null && value !== '') {
            const num = Number(value)
            // if (!isNaN(num)) {
            //     console.log('111111111111')
            //     callback(new Error('经度必须为有效数字'))
            // } else 
            if (num == 0) {
                callback(new Error('经度不能为0'))
            } 
            // else if (!(num > 73 && num < 135)) {
            //     console.log('222222222222')
            //     callback(new Error('经度范围必须在73到135之间（中国范围）'))
            // } 
            else {
                callback()
            }
        } else {
            callback()
        }
    }
    const validateNumberLat = (rule: any, value: any, callback: any) => {
        if (value !== undefined && value !== null && value !== '') {
            const num = Number(value)
            // if (!isNaN(num)) {
            //     callback(new Error('纬度必须为有效数字'))
            // } else 
            if (num == 0) {
                callback(new Error('纬度不能为0'))
            } 
            // else if (!(num > 18 && num < 54)) {
            //     callback(new Error('纬度范围必须在18到54之间（中国范围）'))
            // } 
            else {
                callback()
            }
        } else {
            callback()
        }
    }
    // 规则
    const pointRules = {
        name: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '点位类型不能为空', trigger: 'change' }],
        icon: [{ required: true, message: '图标不能为空', trigger: 'blur' }],
        longitude: [
            // { type: 'number', message: '经度必须为数字', trigger: 'blur' },
            { validator: validateNumberLog, trigger: 'blur' },
            { required: true, message: '经度不能为空', trigger: 'blur' },
        ],
        latitude: [
            // { type: 'number', message: '纬度必须为数字', trigger: 'blur' },
            { validator: validateNumberLat, trigger: 'blur' },
            { required: true, message: '纬度不能为空', trigger: 'blur' },
        ]
    }
    
    // 地图相关状态
    const mapInstance = ref<any>(null)
    const mapLoaded = ref(false)
    // 标点配置弹窗相关
    const pointDialogVisible = ref(false)
    const currentPointIndex = ref(-1)
    const pointForm = reactive({
        name: '',
        type: '',
        longitude: 0,
        latitude: 0,
        icon: ''
    })

    // 函数交互
    // 标点类型配置相关函数
    const openPointTypeConfigDialog = () => {
        pointTypeConfigVisible.value = true
    }
    
    const addPointType = () => {
        currentPointTypeIndex.value = -1
        pointTypeForm.key = ''
        pointTypeForm.name = ''
        pointTypeForm.icon = ''
        pointTypeEditVisible.value = true
    }
    
    const editPointType = (pointType: any, index: number) => {
        currentPointTypeIndex.value = index
        pointTypeForm.key = pointType.key
        pointTypeForm.name = pointType.name
        pointTypeForm.icon = pointType.icon
        pointTypeEditVisible.value = true
    }
    
    const deletePointType = (index: number) => {
        ElMessageBox.confirm('确定要删除这个标点类型吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            pointTypes.value.splice(index, 1)
            ElMessage.success('删除成功')
        })
    }
    
    const pointTypeFormRef = ref()
    const savePointType = async () => {
        if (!pointTypeFormRef.value) return
        
        try {
            await pointTypeFormRef.value.validate()
            
            const typeData = {
                key: pointTypeForm.key,
                name: pointTypeForm.name,
                icon: pointTypeForm.icon
            }
            
            if (currentPointTypeIndex.value >= 0) {
                // 编辑模式
                pointTypes.value[currentPointTypeIndex.value] = typeData
                
                ElMessage.success('标点类型更新成功')
            } else {
                // 新增模式 - 检查key是否已存在
                const existingType = pointTypes.value.find(type => type.key === pointTypeForm.key)
                if (existingType) {
                    ElMessage.warning('类型标识已存在，请使用其他标识')
                    return
                }
                pointTypes.value.push(typeData)
                ElMessage.success('标点类型添加成功')
            }
            updatePointTypes(pointTypes.value)

            pointTypeEditVisible.value = false
        } catch (error) {
            console.log(error)
            ElMessage.warning('请填写完整的标点类型信息')
        }
    }
    const updatePointTypes = async (pointTypes: any) => {
        await updateDataClassify({
            id: 1,
            key: 'module8',
            value: pointTypes
        })
        console.log('保存地图标点图标配置:', pointTypes)
    }
    const handleIconUpload = (response: any) => {
        console.log(response)

        if (response.data && response.data.url) {
            // pointTypeForm.icon = response.data.uri
            pointForm.icon = response.data.uri
            ElMessage.success('图标上传成功')
        }
    }

    const handleIconUploadType = (response: any) => {
        if (response.data && response.data.url) {
            // pointTypeForm.icon = response.data.uri
            pointTypeForm.icon = response.data.uri
            ElMessage.success('图标上传成功')
        }
    }

    
    const removeIcon = () => {
        pointTypeForm.icon = ''
        ElMessage.success('图标已删除')
    }
    
    // 地图标点相关函数
    const openAddPointDialog = async () => {
        currentPointIndex.value = -1
        pointForm.name = ''
        pointForm.type = ''
        pointForm.icon = ''
        pointForm.longitude = 0
        pointForm.latitude = 0
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }

    // 从地图获取坐标
    const getLocationFromMap = () => {
        // 初始化地图（如果还未初始化）
        if (!mapInstance.value && !mapLoaded.value) {
            initMap()
        } else {
            ElMessage.info('请点击地图获取坐标')
        }
    }

    // 初始化高德地图
    const initMap = async () => {
        try {
            // 设置安全密钥 - 必须在AMapLoader.load之前设置
            window._AMapSecurityConfig = {
                securityJsCode: import.meta.env.VITE_AMAP_SECURITY_KEY || '587b22815e6cc6b14effaa607c627fb7'
            }

            // 使用AMapLoader加载高德地图API
            const AMap = await AMapLoader.load({
                key: import.meta.env.VITE_AMAP_KEY || 'e6072f86d2d66d78671eaa4542006354', // 高德地图Web端开发者Key
                version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.ToolBar', 'AMap.Scale'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })

            // 创建地图容器
            const mapContainer = document.getElementById('amap-container')
            if (!mapContainer) {
                ElMessage.error('地图容器未找到')
                return
            }

            // 初始化地图
            const map = new AMap.Map('amap-container', {
                zoom: 12, // 级别
                center: [117.420507, 37.827724], // 中心点坐标，北京
                viewMode: '2D' // 使用2D视图
            })

            mapInstance.value = map
            mapLoaded.value = true

            // 添加地图点击事件监听
            map.on('click', (e: any) => {
                const lnglat = e.lnglat
                pointForm.longitude = Number(lnglat.getLng().toFixed(6))
                pointForm.latitude = Number(lnglat.getLat().toFixed(6))
                ElMessage.success(`已获取坐标：${pointForm.longitude}, ${pointForm.latitude}`)
            })

            ElMessage.success('地图初始化成功，请点击地图获取坐标')
        } catch (error) {
            console.error('地图初始化失败:', error)
            ElMessage.error('地图初始化失败，请检查网络连接或API密钥')
        }
    }

    // 销毁地图实例
    const destroyMap = () => {
        if (mapInstance.value) {
            mapInstance.value.destroy()
            mapInstance.value = null
            mapLoaded.value = false
        }
    }
    // 取消按钮
    const cancelPoint = () => {
        pointDialogVisible.value = false
        destroyMap()
    }

    // 获取点位类型标签样式
    const getPointTypeTag = (type: string) => {
        const tagMap: Record<string, string> = {
            solar: 'primary',
            battery: 'warning',
            travel: 'success',
            transport: 'info'
        }
        return tagMap[type] || 'default'
    }

    // 获取点位类型名称
    const getPointTypeName = (type: string) => {
        const nameMap: Record<string, string> = {
            solar: '绿电供应',
            battery: '共享换电',
            travel: '共享出行',
            transport: '共享运力'
        }
        return nameMap[type] || type
    }

    // 编辑点位
    const editPoint = (point: any, index: number) => {
        currentPointIndex.value = index
        pointForm.name = point.name
        pointForm.type = point.type
        pointForm.icon = point.icon
        pointForm.longitude = point.longitude
        pointForm.latitude = point.latitude
        pointDialogVisible.value = true
        let timer = setTimeout(() => {
            getLocationFromMap()
            clearTimeout(timer)
        }, 500)
    }
    // 删除点位
    const deletePoint = (index: number) => {
        ElMessageBox.confirm('确定要删除这个标点吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            securityForm.mapPoints.splice(index, 1)
            ElMessage.success('删除成功')
        })
    }

    // 切换分类
    const handleTypeChange = (e: any) => {
        console.log(e)
        let obj: any = pointTypes.value.find((item: any) => item.key === e)
        console.log(obj)

        if(obj){
            pointForm.icon = obj.icon
        }else{
            pointForm.icon = ''
        }

    }

    const pointFormRef = ref()
    const savePoint = async () => {
        if (!pointFormRef.value) return
        // console.log(isNaN(pointForm.longitude))
        // console.log(isNaN(pointForm.latitude))

        try {
            await pointFormRef.value.validate()
            if(isNaN(pointForm.longitude) || isNaN(pointForm.latitude)){
                ElMessage.warning('请输入正确的坐标')
                return
            }

            const pointData = {
                name: pointForm.name,
                type: pointForm.type,
                longitude: pointForm.longitude,
                latitude: pointForm.latitude,
                icon: pointForm.icon
            }

            if (currentPointIndex.value >= 0) {
                // 编辑模式
                securityForm.mapPoints[currentPointIndex.value] = pointData
                ElMessage.success('标点更新成功')
            } else {
                // 新增模式
                securityForm.mapPoints.push(pointData)
                ElMessage.success('标点添加成功')
            }

            pointDialogVisible.value = false
        } catch (error) {
            ElMessage.warning('请填写完整的标点信息')
        }
    }


    const securityFormRef = ref()
    const saveSecurityData = async () => {
        if (securityForm.mapPoints.length === 0) {
            ElMessage.warning('请至少添加一个地图标点')
            return
        }
        
        await updateDataClassify({
            id: 1,
            key: 'module5',
            value: securityForm
        })
        console.log('保存地图标点配置:', securityForm)
        ElMessage.success('地图标点配置保存成功')
    }

    const init = async (module: any) => {
        if (module) {
            securityForm.mapPoints = module.module5.mapPoints
            pointTypes.value = module.module8

        }
    }

    defineExpose({
        init
    })
</script>
<style scoped>
.tab-content {
    padding: 20px;
}

.map-points-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.map-points-header h3 {
    margin: 0;
    color: #333;
}

.point-dialog .dialog-content {
    height: 100%;
    width: 100%;
    display: flex;
    gap: 20px;
}

.point-dialog .dialog-content .form-section {
    flex: 1;
}

.point-dialog .dialog-content .form-section h4 {
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
}

.point-dialog .dialog-content .map-section {
    flex: 2;
}

.point-dialog .dialog-content .map-section h4 {
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 8px;
}

.point-dialog .dialog-content .map-section .amap-container {
    width: 100%;
    height: calc(100% - 100px);
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
}

.point-dialog .dialog-content .map-section .map-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.save-button-container {
    text-align: center;
    margin-top: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>